
package com.yuan.graduate;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnCameraChangeListener;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.Projection;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.offlinemap.OfflineMapCity;
import com.amap.api.maps.offlinemap.OfflineMapManager;
import com.amap.api.maps.offlinemap.OfflineMapManager.OfflineMapDownloadListener;
import com.amap.api.maps.offlinemap.OfflineMapStatus;
import com.yuan.adapt.AdaptListUtils;
import com.yuan.adapt.CommAdapt;
import com.yuan.application.BaseActivity;
import com.yuan.control.CheckControl;
import com.yuan.dialog.CustomDialog;
import com.yuan.dialog.CustomProgressDialog;
import com.yuan.dialog.DialogUtil;
import com.yuan.localServer.LocalManage;
import com.yuan.model.M员工信息表;
import com.yuan.model.M请假申请;
import com.yuan.prefence.FileConstants;
import com.yuan.unit.FileUtils;
import com.yuan.unit.ImageUtils;
import com.yuan.unit.NetUtils;
import com.yuan.unit.PreferenceUtil;
import com.yuan.unit.TimeUtils;
import com.yuan.unit.ToastHelper;
import com.yuan.view.Commhead;
import com.yuan.view.NetImageView;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 主界面 MAP MENU
 * 
 * @author YUAN
 */
@SuppressLint("HandlerLeak")
public class MainActivity extends BaseActivity implements OnMarkerClickListener,
        OnInfoWindowClickListener, OnCameraChangeListener, OnMapLoadedListener, OnClickListener,
        InfoWindowAdapter, OnCheckedChangeListener, OfflineMapDownloadListener,
        LocationSource, AMapLocationListener {
    private MapView mapView = null;
    private AMap aMap = null;
    private Context mContext = null;
    private TextView t_realname = null, t_team = null;
    private Commhead main_head;
    private ListView menu_list = null;
    private ImageButton mapcheck_checkin_btn = null, mapcheck_checkout_btn = null;
    private LinearLayout menu_layout = null;
    private RelativeLayout main_view = null;

    private UiSettings mUiSettings = null;
    private LocationManagerProxy mLocationManagerProxy = null;
    private TextView menu_space = null;
    private CustomProgressDialog progessdialog = null, loadMapprogessdialog = null;
    private OfflineMapManager mOfflineMapManager = null;// 离线地图下载控制器
    private MarkerOptions markerOption = null;
    private Marker marker;// 有跳动效果的marker对象
    private OnLocationChangedListener mOnLocationChangedListener;
    private Adapter listItemAdapter = null;
    private List<?> listItemAdapterList = null;
    private NetImageView menu_photo = null;

    private static boolean ISCHECKIN = true;// 上班为true 下班为false
    private static boolean ISCHECKINING = false;
    private boolean isShowMenu = false, isFirstLocation = true;
    private LatLng latlngpoint = null;

    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {// 此方法在ui线程运行

            switch (msg.what) {
                case NOCHECKINADRESS:
                    progessdialog = new CustomProgressDialog(mContext);
                    progessdialog.setUpdateMsg(R.string.locationing);
                    progessdialog.show();
                    break;
                case NOCHECKOUTADRESS:
                    progessdialog = new CustomProgressDialog(mContext);
                    progessdialog.setUpdateMsg(R.string.locationing);
                    progessdialog.show();
                    break;
                case LOCATIONSUCCEEDIN:

                    DialogUtil.createCheckInDialog(mContext, mHandler).show();
                    ISCHECKINING = false;
                    break;
                case LOCATIONSUCCEEDOUT:
                    DialogUtil.createCheckOutDialog(mContext, mHandler).show();
                    ISCHECKINING = false;
                    break;
                case CHECKINSUCCEED:
                    if (progessdialog != null && progessdialog.isShowing()) {
                        progessdialog.dismiss();
                        progessdialog = null;
                    }
                    ToastHelper.getInstance().shortToast(mContext, "上班打卡成功");
                    RefreshButton();
                    break;
                case CHECKINFILED:
                    if (progessdialog != null && progessdialog.isShowing()) {
                        progessdialog.dismiss();
                        progessdialog = null;
                    }
                    ToastHelper.getInstance().shortToast(mContext, "上班打卡失败");
                    break;
                case LOADMAP:
                    LoadOfflineMap();
                    break;
                case CHECKOUTSUCCEED:
                    if (progessdialog != null && progessdialog.isShowing()) {
                        progessdialog.dismiss();
                        progessdialog = null;
                    }
                    ToastHelper.getInstance().shortToast(mContext, "下班打卡成功");
                    RefreshButton();
                    break;
                case CHECKOUTFILED:
                    if (progessdialog != null && progessdialog.isShowing()) {
                        progessdialog.dismiss();
                        progessdialog = null;
                    }
                    ToastHelper.getInstance().shortToast(mContext, "下班打卡失败");
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.map_view);
        mapView.onCreate(savedInstanceState);// 必须要写
        mContext = this;
        init();
        initSlidingMenu();
        initOfflineMap();
        startService(new Intent(SERVER_NAME.LOCAL_SERVER));
    }

    private void LoadOfflineMap() {
        String city = PreferenceUtil.getInstance().getString(USER_CITY, null);
        city = city.replace("市", "");
        boolean flagSuccedToLoadMap = false;
        try {
            flagSuccedToLoadMap = mOfflineMapManager.downloadByCityName(city);
        } catch (com.amap.api.maps.AMapException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (flagSuccedToLoadMap)
        {
            loadMapprogessdialog = new CustomProgressDialog(mContext);
            loadMapprogessdialog.setUpdateMsg(R.string.start_load_offline_map);
            loadMapprogessdialog.show();
        }
    }

    /**
     * 离线地图具体实现
     */
    private void initOfflineMap() {
        // TODO Auto-generated method stub
        // 设置应用单独的地图存储目录，在下载离线地图或初始化地图时设置
        MapsInitializer.sdcardDir = FileUtils.getSdCacheMapDir(this);
        mOfflineMapManager = new OfflineMapManager(this, this);
        if (!NetUtils.isWifiConnected(mContext))
            return;
        try
        {
            boolean agreeToLoadMap = PreferenceUtil.getInstance().getBoolean(AGREEN_TO_LOAD_MAP,
                    true);
            if (!agreeToLoadMap)
                return;
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        String city = PreferenceUtil.getInstance().getString(USER_CITY, null);
        if (city == null || city.length() < 1 || city.equals("null"))
            return;
        boolean isHadOfflineMap = PreferenceUtil.getInstance().getBoolean(HAD_OFFLINE_MAP, false);
        if (isHadOfflineMap)
            return;
        List<OfflineMapCity> list = mOfflineMapManager.getDownloadOfflineMapCityList();
        for (OfflineMapCity mapcity : list)
        {
            if (city.startsWith(mapcity.getCity()) || mapcity.getCity().equals(city))
            {
                PreferenceUtil.getInstance().putString(USER_CITY, city);
                PreferenceUtil.getInstance().putBoolean(HAD_OFFLINE_MAP, true);
                return;
            }
        }
        DialogUtil.createOffLineMapDialog(mContext, mHandler, city).show();
    }

    /**
     * 对侧边的选项栏进行初始化隐藏
     */
    private void initSlidingMenu() {
        menu_layout = (LinearLayout) findViewById(R.id.menu_layout);
        t_realname = (TextView) findViewById(R.id.t_realname);
        t_team = (TextView) findViewById(R.id.t_team);
        menu_space = (TextView) findViewById(R.id.menu_space);
        menu_photo = (NetImageView) findViewById(R.id.menu_photo);
        menu_space.setOnClickListener(this);
        String realname = M员工信息表.getInstance().get姓名();
        String team = M员工信息表.getInstance().get所属队室();
        M请假申请.getInstance().set申请人(M员工信息表.getInstance().get序号() + "");
        if (!TextUtils.isEmpty(realname))
        {
            t_realname.setText(realname);
        }
        if (!TextUtils.isEmpty(team))
        {
            t_team.setText(team);
        }
        menu_photo.setImageUrl(M员工信息表.getInstance().get照片());
        initPhotodialog();
    }

    private void initPhotodialog() {
        // TODO Auto-generated method stub
        final CustomDialog dialog = new CustomDialog(mContext);
        final ListView mPhotolistview = new ListView(mContext);
        Adapter listItemAdapter = new CommAdapt(mContext, createPhotoChoiceList(), "type");
        mPhotolistview.setAdapter((ListAdapter) listItemAdapter);
        mPhotolistview.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                switch (position) {
                    case 0:
                        Intent intentFromCapture = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        intentFromCapture.putExtra(
                                MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(new File(FileConstants.USER_IMAGE)));
                        startActivityForResult(intentFromCapture,
                                CAMERA_REQUEST_CODE);
                        break;
                    case 1:
                        Intent intentFromGallery = new Intent();
                        intentFromGallery.setType("image/*"); // 设置文件类型
                        intentFromGallery
                                .setAction(Intent.ACTION_GET_CONTENT);
                        startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
                        break;
                }
                if (dialog != null && dialog.isShowing())
                {
                    dialog.dismiss();
                }
            }
        });

        dialog.setTitle(R.string.choice_photo_type);
        dialog.addContentView(mPhotolistview);
        dialog.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        menu_photo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.show();
            }
        });
    }

    @SuppressWarnings({
            "rawtypes", "unchecked"
    })
    private List createPhotoChoiceList() {
        // TODO Auto-generated method stub
        List list = new ArrayList();
        Map map = null;
        map = new HashMap();
        map.put("type", "拍照");
        list.add(map);
        map = new HashMap();
        map.put("type", "从文件中选择");
        list.add(map);
        return list;
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        mUiSettings = aMap.getUiSettings();
        aMap.setOnCameraChangeListener(this);// 对amap添加移动地图事件监听器
        mUiSettings.setZoomGesturesEnabled(true);
        mUiSettings.setScrollGesturesEnabled(true);
        mUiSettings.setCompassEnabled(true);
        mUiSettings.setZoomControlsEnabled(true);
        mUiSettings.setScaleControlsEnabled(true);
        aMap.setOnMapLoadedListener(this);// 设置amap加载成功事件监听器
        aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
        aMap.setOnInfoWindowClickListener(this);// 设置点击infoWindow事件监听器
        aMap.setInfoWindowAdapter(this);// 设置自定义InfoWindow样式
        mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);// 设置地图logo显示在底部居中
        isFirstLocation = true;
        aMap.setLocationSource((LocationSource) this);// 设置定位监听
        mUiSettings.setMyLocationButtonEnabled(true); // 是否显示默认的定位按钮
        aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层

        main_view = (RelativeLayout) findViewById(R.id.main_view);
        main_head = (Commhead) findViewById(R.id.main_head);
        main_head.setLeftIcon(R.drawable.menu);
        main_head.setLeftOnClickListener(this);
        mapcheck_checkin_btn = (ImageButton) findViewById(R.id.mapcheck_checkin_btn);
        mapcheck_checkout_btn = (ImageButton) findViewById(R.id.mapcheck_checkout_btn);
        mapcheck_checkin_btn.setOnClickListener(this);
        mapcheck_checkout_btn.setOnClickListener(this);

    }

    public void RefreshButton() {
        if (CheckControl.isCheckedInToday()) {
            mapcheck_checkin_btn
                    .setBackgroundResource(R.drawable.mapcheck_checkin_gray_btn_x);
        } else {
            mapcheck_checkin_btn
                    .setBackgroundResource(R.drawable.mapcheck_checkin_blue_btn_x);
        }
        if (CheckControl.isCheckedOutToday()) {
            mapcheck_checkout_btn
                    .setBackgroundResource(R.drawable.mapcheck_checkout_gray_btn_x);
        } else {
            mapcheck_checkout_btn
                    .setBackgroundResource(R.drawable.mapcheck_checkout_blue_btn_x);
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
        RefreshButton();
        if (listItemAdapter != null)
        {
            ((BaseAdapter) listItemAdapter).notifyDataSetChanged();
        }
        init();
        updateSlidingMenu();
    }

    private void updateSlidingMenu() {
        // TODO Auto-generated method stub
        listItemAdapterList = AdaptListUtils.getInstance().getMenuList();
        menu_list = (ListView) findViewById(R.id.menu_list);
        listItemAdapter = new CommAdapt(mContext, listItemAdapterList, "title");
        menu_list.setAdapter((ListAdapter) listItemAdapter);
        menu_list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                switch (position) {
                    case 0:
                        // 显示地图
                        closeMenu();
                        break;
                    case 1:
                        startActivity(new Intent(mContext, LeaveActivity.class));
                        break;
                    case 2:
                        startActivity(new Intent(mContext, CheckActivity.class));
                        break;
                    case 3:
                        startActivity(new Intent(mContext, SeeLeaveActivity.class));
                        break;
                    case 4:
                        startActivity(new Intent(mContext, TrailActivity.class));
                        break;
                    case 5:
                        startActivity(new Intent(mContext, ChangePsdActivity.class));
                        break;
                    case 6:
                        startActivity(new Intent(mContext, MainSettingActivity.class));
                        break;
                    case 7:
                        // 启动分享界面
                        DialogUtil.createFullAppShareDialog(mContext).show();
                        break;
                    case 8:
                        startActivity(new Intent(mContext, AboutActivity.class));
                        break;
                    case 9:
                        // 退出到登陆界面
                        startActivity(new Intent(mContext, LoginActivity.class));
                        break;
                }
            }
        });

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
        deactivate();
        // stopService(new Intent(SERVER_NAME.LOCAL_SERVER));
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
        outState.putBoolean("isShowMenu", isShowMenu);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        boolean flag = savedInstanceState.getBoolean("isShowMenu", false);
        if (flag) {
            showMenu();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        mapView.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onCameraChange(CameraPosition arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCameraChangeFinish(CameraPosition arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onMyDestroy() {
        mapView.onDestroy();
        super.onMyDestroy();
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.menu_space:
                closeMenu();
                break;
            case R.id.back:
                showMenu();
                break;
            case R.id.mapcheck_checkin_btn:
                ISCHECKINING = true;
                if (LocalManage.getInstance().adress == null
                        || LocalManage.getInstance().adress.length() < 1) {
                    ISCHECKIN = true;
                    mHandler.sendEmptyMessage(NOCHECKINADRESS);
                } else {
                    mHandler.sendEmptyMessage(LOCATIONSUCCEEDIN);
                }

                break;
            case R.id.mapcheck_checkout_btn:
                if (!CheckControl.isCheckedInToday()) {
                    ToastHelper.getInstance().shortToast(mContext, "上班还没有签到！");
                    return;
                }
                ISCHECKINING = true;
                if (LocalManage.getInstance().adress == null
                        || LocalManage.getInstance().adress.length() < 1) {
                    ISCHECKIN = false;
                    mHandler.sendEmptyMessage(NOCHECKOUTADRESS);
                } else {
                    mHandler.sendEmptyMessage(LOCATIONSUCCEEDOUT);
                }

                break;
            default:
                break;
        }

    }

    /**
     * 显示侧部Menu 并加载相应的动画
     */
    private void showMenu() {
        // TODO Auto-generated method stub
        menu_layout.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.page_in_left_right));
        menu_layout.setBackgroundResource(R.drawable.bg);
        menu_layout.setVisibility(View.VISIBLE);
        menu_layout.setClickable(true);
        menu_space.setClickable(true);
        main_view.setClickable(false);
        mapView.setClickable(false);
        mapcheck_checkin_btn.setClickable(false);
        mapcheck_checkout_btn.setClickable(false);
        isShowMenu = true;
        ToastHelper.getInstance().shortToast(mContext, "按返回键返回值主界面");
    }

    /**
     * 关闭侧部Menu 并加载相应的动画
     */
    private void closeMenu() {
        // TODO Auto-generated method stub
        menu_layout.startAnimation(AnimationUtils.loadAnimation(this,
                R.anim.page_out_right_left));
        menu_layout.setVisibility(View.GONE);
        menu_layout.setClickable(false);
        menu_space.setClickable(false);
        main_view.setClickable(true);
        mapcheck_checkin_btn.setClickable(true);
        mapcheck_checkout_btn.setClickable(true);
        mapView.setClickable(true);
        isShowMenu = false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (isShowMenu && keyCode == KeyEvent.KEYCODE_BACK) {
            closeMenu();
            return true;
        }

        if (!isShowMenu && keyCode == KeyEvent.KEYCODE_BACK) {
            startActivity(new Intent(mContext, LoginActivity.class));
            finish();
            return true;
        }

        if (keyCode == KeyEvent.KEYCODE_MENU && !isShowMenu) {
            showMenu();
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_MENU && isShowMenu) {
            closeMenu();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // TODO Auto-generated method stub

    }

    public void onDownload(int status, int completeCode, String downName) {
        switch (status) {
            case OfflineMapStatus.SUCCESS:
                loadMapprogessdialog.setUpdateMsg(R.string.load_offline_map_succeed);
                if (loadMapprogessdialog != null)
                {
                    loadMapprogessdialog.dismiss();
                }
                break;
            case OfflineMapStatus.LOADING:

                if (completeCode == 100)
                {
                    loadMapprogessdialog.setUpdateMsg(R.string.load_offline_map_unzip);
                } else {
                    String tempstr = String.format(
                            mContext.getResources().getString(R.string.load_offline_map_progress),
                            (completeCode + "%"));
                    loadMapprogessdialog.setUpdateMsg(tempstr);
                }
                break;
            case OfflineMapStatus.UNZIP:
                loadMapprogessdialog.setUpdateMsg(R.string.load_offline_map_unzip);
                break;
            case OfflineMapStatus.WAITING:
                break;
            case OfflineMapStatus.PAUSE:
                break;
            case OfflineMapStatus.STOP:
                break;
            case OfflineMapStatus.ERROR:
                loadMapprogessdialog.setUpdateMsg(R.string.load_offline_map_failed);
                if (loadMapprogessdialog != null)
                {
                    loadMapprogessdialog.dismiss();
                }
                break;
            default:
                break;
        }
    }

    private void updateMap() {
        // TODO Auto-generated method stub
        aMap.clear();
        markerOption = new MarkerOptions();
        markerOption.position(latlngpoint);
        markerOption.title("当前时间：" + TimeUtils.getNowTime()).snippet(
                "当前地点：" + LocalManage.getInstance().adress);
        markerOption.perspective(true);
        markerOption.draggable(true);
        markerOption.icon(BitmapDescriptorFactory
                .fromResource(R.drawable.arrow));
        marker = aMap.addMarker(markerOption);
    }

    @Override
    public boolean onMarkerClick(final Marker marker) {
        if (marker.equals(marker)) {
            if (aMap != null) {
                jumpPoint(marker);
            }
        }
        return false;
    }

    /**
     * marker点击时跳动一下
     */
    public void jumpPoint(final Marker marker) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();

        Projection proj = aMap.getProjection();
        Point startPoint = proj.toScreenLocation(latlngpoint);
        startPoint.offset(0, -100);
        final LatLng startLatLng = proj.fromScreenLocation(startPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);
                double lng = t * latlngpoint.longitude + (1 - t)
                        * startLatLng.longitude;
                double lat = t * latlngpoint.latitude + (1 - t)
                        * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));
                if (t < 1.0) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }

    @Override
    public View getInfoContents(Marker arg0) {
        View infoContent = getLayoutInflater().inflate(
                R.layout.custom_dialog_contents, null);
        render(marker, infoContent);
        return infoContent;
    }

    /**
     * 自定义infowinfow窗口
     */
    public void render(Marker marker, View view) {
        String title = marker.getTitle();
        TextView titleUi = ((TextView) view.findViewById(R.id.title));
        if (title != null) {
            SpannableString titleText = new SpannableString(title);
            titleUi.setText(titleText);
        } else {
            titleUi.setText("");
        }
        String snippet = marker.getSnippet();
        TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
        if (snippet != null) {
            SpannableString snippetText = new SpannableString(snippet);
            snippetUi.setText(snippetText);
        } else {
            snippetUi.setText("");
        }
    }

    @Override
    public View getInfoWindow(Marker arg0) {
        View infoContent = getLayoutInflater().inflate(
                R.layout.custom_dialog_contents, null);
        render(marker, infoContent);
        return infoContent;
    }

    @Override
    public void onMapLoaded() {

    }

    @Override
    public void onInfoWindowClick(Marker arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onLocationChanged(AMapLocation aLocation) {
        // TODO Auto-generated method stub
        if (mOnLocationChangedListener != null) {
            mOnLocationChangedListener.onLocationChanged(aLocation);// 显示系统小蓝点
            Bundle locBundle = aLocation.getExtras();
            LocalManage.getInstance().adress = locBundle.getString("desc");
            if (ISCHECKINING) {
                if (ISCHECKIN) {
                    mHandler.sendEmptyMessage(LOCATIONSUCCEEDIN);
                }
                else {
                    mHandler.sendEmptyMessage(LOCATIONSUCCEEDOUT);
                }
            }
            double lng = aLocation.getLongitude();
            double lat = aLocation.getLatitude();
            LocalManage.getInstance().lat = lat;
            LocalManage.getInstance().lng = lng;
            latlngpoint = new LatLng(lat, lng);
            if (isFirstLocation) {
                CameraUpdate cameraupdate = CameraUpdateFactory.newLatLngZoom(
                        latlngpoint, ZOOM);
                aMap.animateCamera(cameraupdate);
                isFirstLocation = false;
            }
            updateMap();
        }
    }

    @Override
    public void activate(OnLocationChangedListener listener) {
        mOnLocationChangedListener = listener;
        if (mLocationManagerProxy == null) {
            mLocationManagerProxy = LocationManagerProxy.getInstance(this);
            mLocationManagerProxy.requestLocationUpdates(
                    LocationProviderProxy.AMapNetwork, 5000, 10, this);
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mOnLocationChangedListener = null;
        if (mLocationManagerProxy != null) {
            mLocationManagerProxy.removeUpdates(this);
            mLocationManagerProxy.destory();
        }
        mLocationManagerProxy = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case IMAGE_REQUEST_CODE:
                try
                {
                    startPhotoZoom(data.getData());
                } catch (NullPointerException e)
                {// 没有选择照片
                    e.printStackTrace();
                }

                break;
            case CAMERA_REQUEST_CODE:
                File tempFile = new File(FileConstants.USER_IMAGE);
                startPhotoZoom(Uri.fromFile(tempFile));
                break;
            case RESULT_REQUEST_CODE:
                if (data != null) {
                    getImageToView(data);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    public void startPhotoZoom(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 320);
        intent.putExtra("outputY", 320);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 2);
    }

    /**
     * 保存裁剪之后的图片数据
     * 
     * @param picdata
     */
    private void getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            final Bitmap photo = extras.getParcelable("data");
            menu_photo.setImageBitmap(photo);
            new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void... params) {
                    // TODO Auto-generated method stub
                    if (FileUtils.isFileExist(FileConstants.USER_IMAGE))
                    {
                        FileUtils.deleteFile(FileConstants.USER_IMAGE);
                    }
                    ImageUtils.saveBitmapToFileSystem(mContext, LOCAL_PATH_IMAGES, "user.png",
                            photo);
                    M员工信息表.getInstance().uploadPhoto(mContext);
                    return null;
                }
            }.execute();
        }
    }
}
